import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Row, 
  Col, 
  Button, 
  Space, 
  Progress, 
  Tag, 
  List, 
  Avatar,
  message,
  Spin,
  Divider,
  Typography
} from 'antd';
import { 
  PlayCircleOutlined, 
  PauseCircleOutlined,
  FullscreenOutlined,
  DownloadOutlined,
  EyeOutlined,
  ClockCircleOutlined,
  BookOutlined
} from '@ant-design/icons';
import { useParams } from 'react-router-dom';
import './index.scss';
import { request } from '@/utils/api';

const { Title, Text } = Typography;

const LessonReplay = () => {
  const { courseId, lessonId, studentId } = useParams();
  
  const [lessonData, setLessonData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [videoProgress, setVideoProgress] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [selectedQuality, setSelectedQuality] = useState('720p');
  const [selectedSubtitle, setSelectedSubtitle] = useState('zh-CN');

  useEffect(() => {
    if (courseId && lessonId && studentId) {
      fetchLessonData();
    }
  }, [courseId, lessonId, studentId]);

  // 获取课时数据
  const fetchLessonData = async () => {
    setLoading(true);
    try {
      const data = await request(`/lesson/courses/${courseId}/lessons/${lessonId}?user_id=${studentId}`);

      if (data.code === 200) {
        setLessonData(data.data);
        setDuration(data.data.lesson.duration || 0);
        
        // 如果有观看记录，设置播放位置
        if (data.data.view_record?.last_position) {
          setCurrentTime(data.data.view_record.last_position);
        }
      } else {
        message.error(data.message || '获取课时信息失败');
      }
    } catch (error) {
      console.error('获取课时信息失败:', error);
      message.error('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 更新观看进度
  const updateProgress = async (progress, position) => {
    try {
      const data = await request(`/lesson/courses/${courseId}/lessons/${lessonId}/progress`, {
        method: 'POST',
        body: JSON.stringify({
          user_id: studentId,
          progress: progress,
          position: position,
          watch_time: 30 // 假设每30秒更新一次
        })
      });

      if (data.code !== 200) {
        console.error('更新进度失败:', data.message);
      }
    } catch (error) {
      console.error('更新进度失败:', error);
    }
  };

  // 处理播放/暂停
  const handlePlayPause = () => {
    setIsPlaying(!isPlaying);
    // 这里应该控制视频播放器
  };

  // 处理进度变化
  const handleProgressChange = (percent) => {
    const newTime = (percent / 100) * duration;
    setCurrentTime(newTime);
    setVideoProgress(percent);
    
    // 更新观看进度
    updateProgress(percent, newTime);
  };

  // 处理全屏
  const handleFullscreen = () => {
    // 这里应该控制视频全屏
    console.log('全屏播放');
  };

  // 处理下载
  const handleDownload = () => {
    if (lessonData?.replay?.video_url) {
      const link = document.createElement('a');
      link.href = lessonData.replay.video_url;
      link.download = `${lessonData.lesson.title}.mp4`;
      link.click();
    }
  };

  // 跳转到章节
  const handleChapterClick = (time) => {
    const percent = (time / duration) * 100;
    handleProgressChange(percent);
  };

  if (loading) {
    return (
      <div className="lesson-replay-loading">
        <Spin size="large" />
        <Text>加载中...</Text>
      </div>
    );
  }

  if (!lessonData) {
    return (
      <div className="lesson-replay-error">
        <Text type="danger">课时信息不存在</Text>
      </div>
    );
  }

  return (
    <div className="lesson-replay">
      <Row gutter={24}>
        {/* 视频播放区域 */}
        <Col span={16}>
          <Card className="video-card">
            {/* 视频播放器 */}
            <div className="video-player">
              <div className="video-container">
                <video
                  src={lessonData.replay?.video_url}
                  controls
                  width="100%"
                  height="400"
                  poster={lessonData.course?.cover}
                />
              </div>
              
              {/* 播放控制栏 */}
              <div className="video-controls">
                <div className="control-left">
                  <Button 
                    type="text" 
                    icon={isPlaying ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
                    onClick={handlePlayPause}
                  />
                  <span className="time-display">
                    {Math.floor(currentTime / 60)}:{(currentTime % 60).toString().padStart(2, '0')} / 
                    {Math.floor(duration / 60)}:{(duration % 60).toString().padStart(2, '0')}
                  </span>
                </div>
                
                <div className="control-center">
                  <Progress 
                    percent={videoProgress} 
                    showInfo={false}
                    onChange={handleProgressChange}
                    strokeColor="#1890ff"
                  />
                </div>
                
                <div className="control-right">
                  <Space>
                    <Button 
                      type="text" 
                      icon={<DownloadOutlined />}
                      onClick={handleDownload}
                    />
                    <Button 
                      type="text" 
                      icon={<FullscreenOutlined />}
                      onClick={handleFullscreen}
                    />
                  </Space>
                </div>
              </div>
            </div>

            {/* 课时信息 */}
            <div className="lesson-info">
              <Title level={3}>{lessonData.lesson.title}</Title>
              <Text type="secondary">{lessonData.lesson.description}</Text>
              
              <div className="lesson-meta">
                <Space>
                  <Tag icon={<ClockCircleOutlined />}>
                    {Math.floor(lessonData.lesson.duration / 60)}分钟
                  </Tag>
                  <Tag icon={<BookOutlined />}>
                    {lessonData.course?.title}
                  </Tag>
                  {lessonData.lesson.is_free && (
                    <Tag color="green">免费</Tag>
                  )}
                </Space>
              </div>
            </div>

            {/* 章节导航 */}
            {lessonData.replay?.chapters && (
              <div className="chapters-section">
                <Title level={4}>章节导航</Title>
                <List
                  size="small"
                  dataSource={lessonData.replay.chapters}
                  renderItem={(chapter, index) => (
                    <List.Item 
                      className="chapter-item"
                      onClick={() => handleChapterClick(chapter.time)}
                    >
                      <Space>
                        <Text>{index + 1}.</Text>
                        <Text>{chapter.title}</Text>
                        <Text type="secondary">
                          {Math.floor(chapter.time / 60)}:{(chapter.time % 60).toString().padStart(2, '0')}
                        </Text>
                      </Space>
                    </List.Item>
                  )}
                />
              </div>
            )}
          </Card>
        </Col>

        {/* 侧边栏 */}
        <Col span={8}>
          {/* 观看记录 */}
          {lessonData.view_record && (
            <Card title="观看记录" className="view-record-card">
              <div className="record-item">
                <Text>观看进度</Text>
                <Progress 
                  percent={lessonData.view_record.progress || 0} 
                  size="small"
                  format={(percent) => `${percent}%`}
                />
              </div>
              <div className="record-item">
                <Text>观看时长</Text>
                <Text strong>
                  {Math.floor((lessonData.view_record.watch_time || 0) / 60)}分钟
                </Text>
              </div>
              <div className="record-item">
                <Text>观看次数</Text>
                <Text strong>{lessonData.view_record.watch_count || 0}次</Text>
              </div>
              <div className="record-item">
                <Text>最后观看</Text>
                <Text strong>
                  {lessonData.view_record.last_watch_at ? 
                    new Date(lessonData.view_record.last_watch_at).toLocaleString() : 
                    '未观看'
                  }
                </Text>
              </div>
            </Card>
          )}

          {/* 视频设置 */}
          <Card title="视频设置" className="video-settings-card">
            <div className="setting-item">
              <Text>清晰度</Text>
              <Space>
                {lessonData.replay?.quality?.map(quality => (
                  <Button
                    key={quality}
                    type={selectedQuality === quality ? 'primary' : 'default'}
                    size="small"
                    onClick={() => setSelectedQuality(quality)}
                  >
                    {quality}
                  </Button>
                ))}
              </Space>
            </div>
            
            {lessonData.replay?.subtitles && (
              <div className="setting-item">
                <Text>字幕</Text>
                <Space>
                  {lessonData.replay.subtitles.map(subtitle => (
                    <Button
                      key={subtitle.language}
                      type={selectedSubtitle === subtitle.language ? 'primary' : 'default'}
                      size="small"
                      onClick={() => setSelectedSubtitle(subtitle.language)}
                    >
                      {subtitle.language === 'zh-CN' ? '中文' : 'English'}
                    </Button>
                  ))}
                </Space>
              </div>
            )}
          </Card>

          {/* 附件下载 */}
          {lessonData.lesson.attachments && lessonData.lesson.attachments.length > 0 && (
            <Card title="课程资料" className="attachments-card">
              <List
                size="small"
                dataSource={lessonData.lesson.attachments}
                renderItem={attachment => (
                  <List.Item>
                    <Button 
                      type="link" 
                      icon={<DownloadOutlined />}
                      onClick={() => {
                        const link = document.createElement('a');
                        link.href = attachment.url;
                        link.download = attachment.name;
                        link.click();
                      }}
                    >
                      {attachment.name}
                    </Button>
                  </List.Item>
                )}
              />
            </Card>
          )}
        </Col>
      </Row>
    </div>
  );
};

export default LessonReplay; 